﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using Studio77.GuessLyric.Views;
using Studio77.GuessLyric.Core;
using System.Windows.Media.Imaging;
using System.Text;
using OpenXLive;
using System.IO;
using OpenXLiveSilverlight;
using System.Diagnostics;
using CN.SmartMad.Ads.WindowsPhone.WPF;
using Microsoft.Phone.Tasks;
using System.Windows.Threading;

namespace Studio77.GuessLyric.Pages
{
    public partial class GamePage : PhoneApplicationPage
    {
        public static GamePage Instance = null;

        List<DaanItem> daanItems = new List<DaanItem>();
        List<KeyItem> keyItems = new List<KeyItem>();
        List<String> currDaan = new List<string>();

        bool isComplete = false;
        bool isLoaded = false;
        string quesDaanStr = string.Empty;

        DispatcherTimer mokaAdsSwitchTimer;
        int currentMokaAdIndex = 0;
        int totalMokaAdCount = 2;

        bool usemoka = true;

        public GamePage()
        {
            InitializeComponent();
            Instance = this;
        }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);
            if (!isLoaded)
            {
                UpdateUI();
            }

            //魔卡广告切换Timer
            mokaAdsSwitchTimer = new DispatcherTimer();

            //获取间隔参数
            int intervalSec = 30;
            string secStr = UmengSDK.UmengAnalytics.GetOnlineParam("moka_banner_switch_sec");
            if (!int.TryParse(secStr, out intervalSec))
            {
                intervalSec = 30;
            }

            mokaAdsSwitchTimer.Interval = TimeSpan.FromSeconds(intervalSec);
            mokaAdsSwitchTimer.Tick += mokaAdsSwitchTimer_Tick;
            mokaAdsSwitchTimer.Start();

            bool useSmartmad = true;
            String usemokaStr = UmengSDK.UmengAnalytics.GetOnlineParam("usemoka");
            //0-关闭 1-同时开启 2-开启banner 3-开启开屏
            if (usemokaStr == "1" || usemokaStr == "2")
            {
                usemoka = true;
                if (StageManager.Instance.TurnMoka)
                {
                    //移动moka到最前面，而且不显示亿动
                    gridRoot.Children.Remove(imgBanner);
                    gridRoot.Children.Add(imgBanner);
                    useSmartmad = false;
                }
                StageManager.Instance.TurnMoka = !StageManager.Instance.TurnMoka;
                currentMokaAdIndex = 0;
                switchMokaAdImage();
            }
            else if (usemokaStr == "0" || usemokaStr == "3")
            {
                this.imgBanner.Visibility = System.Windows.Visibility.Collapsed;
                usemoka = false;
            }
            else
            {
                usemoka = false;
            }


            if (useSmartmad)
            {
                InitSmartMadAd();
            }
            else
            {
                gridMsnAd.Visibility = System.Windows.Visibility.Collapsed;
            }

        }

        /// <summary>
        /// 更新魔卡广告的banner
        /// </summary>
        private void switchMokaAdImage()
        {
            BitmapImage bitmap = new BitmapImage(new Uri(@"\Images\banner" + (currentMokaAdIndex + 1).ToString() + ".jpg", UriKind.RelativeOrAbsolute));
            this.imgBanner.Source = bitmap;
        }

        void mokaAdsSwitchTimer_Tick(object sender, EventArgs e)
        {
            currentMokaAdIndex++;
            currentMokaAdIndex = currentMokaAdIndex % totalMokaAdCount;
            switchMokaAdImage();
        }

        protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e)
        {
            base.OnBackKeyPress(e);
            if (isComplete)
            {
                StageManager.Instance.TrunNext();
            }
        }

        private void UpdateUI()
        {
            isComplete = false;

            this.gridComplete.Visibility = System.Windows.Visibility.Collapsed;
            this.txtCoinCount.Text = StageManager.Instance.TotalG.ToString();
            this.txtCurrentStage.Text = StageManager.Instance.LastStage.ToString();

            string titleUri = "/Images/guessType1.png";
            //设置答案区域
            this.stackDaan.Children.Clear();
            daanItems.Clear();
            keyItems.Clear();
            currDaan.Clear();

            var question = StageManager.Instance.GetQuestionInfo();
            if (question.Type == 1)
            {
                titleUri = "/Images/guessType1.png";
                this.imgQuesType.Source = new BitmapImage(new Uri(titleUri, UriKind.RelativeOrAbsolute));
                this.txtSinger.Text = question.Singer;
                this.txtSong.Visibility = System.Windows.Visibility.Collapsed;
                this.imgSong.Visibility = System.Windows.Visibility.Collapsed;
                this.txtSinger.Visibility = System.Windows.Visibility.Visible;
                this.imgSinger.Visibility = System.Windows.Visibility.Visible;

                StringBuilder sb = new StringBuilder("歌词：" + Environment.NewLine);
                foreach (var item in question.LyricStrList)
                {
                    sb.AppendLine(item);
                }

                quesDaanStr = question.SongName;

                this.txtContent.Text = sb.ToString();
                for (int i = 0; i < quesDaanStr.Length; i++)
                {
                    DaanItem item = new DaanItem();
                    daanItems.Add(item);
                    this.stackDaan.Children.Add(item);

                    currDaan.Add(string.Empty);
                    keyItems.Add(null);
                }
            }
            else if (question.Type == 2)
            {
                titleUri = "/Images/guessType2.png";
                this.imgQuesType.Source = new BitmapImage(new Uri(titleUri, UriKind.RelativeOrAbsolute));
                this.txtSinger.Text = question.Singer;
                this.txtSong.Text = question.SongName;
                this.txtSong.Visibility = System.Windows.Visibility.Visible;
                this.imgSong.Visibility = System.Windows.Visibility.Visible;
                this.txtSinger.Visibility = System.Windows.Visibility.Visible;
                this.imgSinger.Visibility = System.Windows.Visibility.Visible;

                StringBuilder sb = new StringBuilder("歌词：" + Environment.NewLine);
                for (int i = 0; i < question.LyricStrList.Count; i++)
                {
                    string geci = question.LyricStrList[i];
                    if (i == (question.GuessLyricIndex - 1))
                    {
                        sb.AppendLine("___________________");
                    }
                    else
                    {
                        sb.AppendLine(geci);
                    }
                }

                quesDaanStr = question.LyricStrList[question.GuessLyricIndex - 1];

                this.txtContent.Text = sb.ToString();
                for (int i = 0; i < quesDaanStr.Length; i++)
                {
                    DaanItem item = new DaanItem();
                    daanItems.Add(item);
                    this.stackDaan.Children.Add(item);

                    currDaan.Add(string.Empty);
                    keyItems.Add(null);
                }
            }

            //设置键盘提示区
            this.keyboard.SetKeyBoardContent(StageManager.Instance.GetBeixuanDaan());

            isLoaded = true;
        }

        private void btnBack_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            if (this.NavigationService.CanGoBack)
            {
                this.NavigationService.GoBack();
            }
            else
            {
                this.NavigationService.Navigate(new Uri("/MainPage.xaml", UriKind.RelativeOrAbsolute));
            }
        }



        internal void OnKeyboard(Views.KeyItem key)
        {
            for (int i = 0; i < currDaan.Count; i++)
            {
                if (string.IsNullOrEmpty(currDaan[i]))
                {
                    currDaan[i] = key.GetChar();
                    keyItems[i] = key;
                    daanItems[i].SetContent(key.GetChar());
                    break;
                }
            }
            //检查答案是否正确
            if (quesDaanStr.ToLower() == GetDaanStr().ToLower())
            {
                SoundManager.PlayEffect(SoundManager.coin);
                //显示结束画面
                this.txtDaan.Text = quesDaanStr;
                this.gridComplete.Visibility = System.Windows.Visibility.Visible;
                this.txtAddCoin.Text = "+ 10";
                StageManager.Instance.TotalG += 10;
                isComplete = true;
            }
        }

        private string GetDaanStr()
        {
            String result = string.Empty;
            for (int i = 0; i < currDaan.Count; i++)
            {
                result += currDaan[i];
            }
            return result;
        }

        internal void ClearOneChar(DaanItem daanItem)
        {
            int index = daanItems.IndexOf(daanItem);
            keyItems[index].IsEnabled = true;
            keyItems[index] = null;
            currDaan[index] = string.Empty;

        }

        public bool IsCanTypeNewChar()
        {
            bool result = false;
            for (int i = 0; i < currDaan.Count; i++)
            {
                if (string.IsNullOrEmpty(currDaan[i]))
                {
                    result = true;
                    break;
                }
            }
            return result;
        }

        private void btnTip_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            SoundManager.PlayEffect(SoundManager.enter);
            if (StageManager.Instance.TotalG >= 50)
            {
                StageManager.Instance.TotalG -= 50;
                //显示结束画面
                this.txtDaan.Text = quesDaanStr;
                this.gridComplete.Visibility = System.Windows.Visibility.Visible;
                this.txtAddCoin.Text = "+ 0";
                isComplete = true;
            }
            else
            {
                MessageBox.Show("金币不足");
            }
        }

        private void btnNext_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            SoundManager.PlayEffect(SoundManager.enter);
            //进入下一题
            if (StageManager.Instance.TrunNext())
            {
                //进入下个关卡
                UpdateUI();
            }
            else
            {
                MessageBox.Show("太厉害了！这已经是最后一题喽，请关注更新版本。");
            }
        }

        private void btnShare_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            SoundManager.PlayEffect(SoundManager.enter);
            if (XLiveGameManager.CurrentSession != null &&
                XLiveGameManager.CurrentSession.SNSProviders.Count > 0) // Must exist available provider
            {
                WriteableBitmap wb = new WriteableBitmap(gridRoot, null);
                MemoryStream ms = new MemoryStream();
                wb.SaveJpeg(ms, (int)gridRoot.ActualWidth, (int)gridRoot.ActualHeight, 0, 70);
                ms.Seek(0, SeekOrigin.Begin);
                byte[] pic = new byte[ms.Length];
                int count = ms.Read(pic, 0, pic.Length);
                ms.Close();

                UpdateStatus(pic);
            }
        }

        // Share the screenshot
        private void UpdateStatus(byte[] picture)
        {
            if (XLiveGameManager.CurrentSession != null)
            {
                UpdateStatusPage.SharingPicture = picture;
                this.NavigationService.Navigate(new Uri("/Pages/UpdateStatusPage.xaml", UriKind.RelativeOrAbsolute));
            }
        }

        #region 亿动广告

        private void InitSmartMadAd()
        {
            //  实例化SmartMad Banner容器
            SMAdBannerView banner = new SMAdBannerView("90040207");
            //  设置Banner广告刷新过场动画类型(可选)
            banner.AdBannerAnimationType =
            SMAdBannerAnimationType.BANNER_ANIMATION_TYPE_FADEINOUT;
            //  设置Banner广告事件
            banner.AdBannerClicked += new EventHandler(banner_AdBannerClicked);
            banner.AdBannerWillExpand += new EventHandler(banner_AdBannerWillExpand);
            banner.AdBannerExpandClosed += new
            EventHandler(banner_AdBannerExpandClosed);
            banner.AdBannerReceived += new EventHandler(banner_AdBannerReceived);
            banner.AdBannerReceiveFailed += new
            EventHandler<SMAdEventCode>(banner_AdBannerReceiveFailed);
            banner.AdBannerPresentingScreen += new
            EventHandler<SMAdEventCode>(banner_AdBannerPresentingScreen);
            banner.AdBannerLeaveApplication += new
            EventHandler(banner_AdBannerLeaveApplication);
            banner.AppWillSuspendForAd += new
            EventHandler(banner_AppWillSuspendForAd);
            banner.AppWillResumeFromAd += new
            EventHandler(banner_AppWillResumeFromAd);
            banner.AdBannerDismissScreen += new
            EventHandler(banner_AdBannerDismissScreen);
            //  将Banner容器加入界面
            gridMsnAd.Children.Add(banner);
        }

        private void banner_AdBannerDismissScreen(object sender, EventArgs e)
        {

        }

        private void banner_AppWillResumeFromAd(object sender, EventArgs e)
        {

        }

        private void banner_AppWillSuspendForAd(object sender, EventArgs e)
        {

        }

        private void banner_AdBannerLeaveApplication(object sender, EventArgs e)
        {

        }

        private void banner_AdBannerPresentingScreen(object sender, SMAdEventCode e)
        {

        }

        private void banner_AdBannerReceiveFailed(object sender, SMAdEventCode e)
        {

        }

        private void banner_AdBannerReceived(object sender, EventArgs e)
        {
            //接收成功，隐藏微软广告
            Dispatcher.BeginInvoke(() =>
            {
                if (adControlMicrosoft != null)
                {
                    this.gridRoot.Children.Remove(adControlMicrosoft);
                    adControlMicrosoft = null;
                }
            });
        }

        private void banner_AdBannerExpandClosed(object sender, EventArgs e)
        {

        }

        private void banner_AdBannerWillExpand(object sender, EventArgs e)
        {

        }

        private void banner_AdBannerClicked(object sender, EventArgs e)
        {

        }

        private void imgBanner_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            WebBrowserTask webBrowserTask = new WebBrowserTask();
            if (currentMokaAdIndex == 0)
            {
                //跳转到魔卡幻想
                webBrowserTask.Uri = new Uri("http://bj.adserve.ifreeteam.com:9090/advertise/ad/receive.json?id=c035da4065183dbec79ffbe43fa11301ac619c2b8fdd723b692ae4b7915b3ce7", UriKind.Absolute);
            }
            else
            {
                //跳转到千魔斩
                webBrowserTask.Uri = new Uri("http://bj.adserve.ifreeteam.com:9090/advertise/ad/receive.json?id=5fc22bb64e05cb93477f153d9d61cb409179c3036db5ba85446dde582ec3c345", UriKind.Absolute);
            }
            webBrowserTask.Show();
        }

        #endregion

        //void InitMsnAd()
        //{
        //    string adSpaceId = "NzUwfDc5OHwyNDkyfDE=";//M3wxfDF8MQ==为测试Id，仅限于测试时使用，不参与计费

        //    Thickness adPosition = new Thickness();//定义广告banner的位置。

        //    adPosition.Left = 0;
        //    adPosition.Top = 0;
        //    adPosition.Right = 0;
        //    adPosition.Bottom = 0;
        //    AdControl adControl = new AdControl(this);
        //    adControl.InitAd(adPosition, adSpaceId);//初始化广告banner
        //    adControl.AdReveiceEvent += new AdReveiceHandler(adControl_AdReveiceEvent);//广告接收成功事件
        //    adControl.AdFailedEvent += new AdFailedHandler(adControl_AdFailedEvent);//广告接收失败事件
        //    adControl.LeaveApplicationEvent += new LeaveApplicationHandler(LeaveApplicationHandler);//广告即将离开应用程序事件
        //    adControl.PresentScreenEvent += new PresentScreenHandler(adControl_PresentScreenEvent);//广告即将跳转网页事件
        //    adControl.DismissScreenEvent += new DismissScreenHandler(adControl_DismissScreenEvent);//广告网页即将返回事件
        //    gridMsnAd.Children.Add(adControl);//注意：不要忘了将广告banner加到应用程序中。
        //    adControl.LoadAd();//开始请求广告
        //}

        //public void adControl_AdReveiceEvent(AdControl adControl)
        //{
        //    Debug.WriteLine("---------MSNLog--------adView_AdReveiceEvent");//简单的打印当前广告状态，开发者可以根据广告的状态来调整应用的状态等

        //    Dispatcher.BeginInvoke(() =>
        //        {
        //            if (adControlMicrosoft != null)
        //            {
        //                this.gridRoot.Children.Remove(adControlMicrosoft);
        //                adControlMicrosoft = null;
        //            }
        //        });
        //}
        //public void adControl_PresentScreenEvent(AdControl adControl)
        //{
        //    Debug.WriteLine("---------MSNLog--------adView_PresentScreenEvent");//简单的打印当前广告状态，开发者可以根据广告的状态来调整应用的状态等
        //}
        //public void adControl_DismissScreenEvent(AdControl adControl)
        //{
        //    Debug.WriteLine("---------MSNLog--------adControl_DismissScreenEvent");//简单的打印当前广告状态，开发者可以根据广告的状态来调整应用的状态等
        //}
        //public void adControl_AdFailedEvent(ErrorCode errorCode, AdControl adControl)
        //{
        //    Debug.WriteLine("---------MSNLog--------adView_AdFailedEvent errorCode: {0}", errorCode);//简单的打印当前广告状态，开发者可以根据广告的状态来调整应用的状态等
        //}
        //public void LeaveApplicationHandler(AdControl adControl)
        //{
        //    Debug.WriteLine("---------MSNLog--------LeaveApplicationHandler");//简单的打印当前广告状态，开发者可以根据广告的状态来调整应用的状态等
        //}
    }
}